package com.jixi.controller;

import com.jixi.common.exception.FileUploadException;
import com.jixi.common.result.Result;
import com.jixi.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

//文件上传，使用MinIO对象存储服务器
@RestController
@RequestMapping("/education")
public class FileUploadController {
	
	@Autowired
	private MinioConfig minioConfig;
	
	@Autowired
	private MinioClient minioClient;
	
	/**
	 * 文件上传
	 *
	 * @param file 文件
	 * @return 上传结果
	 * @throws IOException         IO异常
	 * @throws FileUploadException 文件上传异常
	 */
	@PostMapping("/upload")
	public Result<String> upload(@RequestParam("file") MultipartFile file) throws FileUploadException, IOException {
		
		//文件名配置
		String originalFilename = file.getOriginalFilename();
		String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
		
		//构建文件上传信息
		PutObjectArgs args = PutObjectArgs.builder()
				.bucket(minioConfig.getBucketName())
				.object(filename)
				.stream(file.getInputStream(), file.getSize(), - 1)
				.contentType(file.getContentType())
				.build();
		
		try {
			//将文件上传到minio服务器
			minioClient.putObject(args);
			
			//组装文件信息
			String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + filename;
			
			return Result.success(url);
			
		} catch (Exception e) {
			throw new FileUploadException("文件上传异常");
		}
	}
	
}
